package com.zwg.git_customview.mp4

import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import com.zwg.git_customview.R


import android.graphics.SurfaceTexture
import android.view.Surface
import android.view.TextureView
import androidx.appcompat.app.AppCompatActivity
import java.io.IOException


class VideoActivity : AppCompatActivity() {

    private lateinit var textureView: TextureView
    private var mediaPlayer: MediaPlayer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_textureview)

        textureView = findViewById(R.id.texture_view)
        textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
            override fun onSurfaceTextureAvailable(
                surface: SurfaceTexture,
                width: Int,
                height: Int
            ) {
                val s = Surface(surface)
                mediaPlayer = MediaPlayer().apply {
                    try {
                        // 设置本地视频文件的路径
                        val videoUri =
                            Uri.parse("android.resource://${packageName}/${R.raw.splash_video}")
                        setDataSource(this@VideoActivity, videoUri)
                        setSurface(s)
                        prepare()
                        start()

                        // 设置循环播放
                        isLooping = true
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }

            override fun onSurfaceTextureSizeChanged(
                surface: SurfaceTexture,
                width: Int,
                height: Int
            ) {
            }

            override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
                mediaPlayer?.release()
                mediaPlayer = null
                return true
            }

            override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer?.release()
        mediaPlayer = null
    }
}
